package com.gy.hadoop.juc.thread;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 传统锁机制生产者消费者模型
 * <p>
 * 初始值为0的变量，两个线程交替操作，一个+1，一个-1，执行五轮
 * 1 线程  操作  资源类
 * 2 判断  干活  通知
 * 3 防止虚假唤醒机制
 */
public class ProdConsMyLock {

    public static void main(String[] args) {
        Resource resource = new Resource();
        for (int i = 0; i < 5; i++) {
            new Thread(() -> {
                for (int i1 = 0; i1 < 10; i1++) {
                    resource.produce();
                }
            }, "prod_" + i).start();
        }

        for (int i = 0; i < 5; i++) {
            new Thread(() -> {
                for (int i1 = 0; i1 < 10; i1++) {
                    resource.consumer();
                }
            }, "cons_" + i).start();
        }
    }


}


class Resource {

    ReentrantLock lock = new ReentrantLock();
    Condition condition = lock.newCondition();

    //共享变量
    private int num = 0;

    void consumer() {
        //加锁
        lock.lock();
        try {
            //1 判断
            for (; num == 0; condition.await()) {
                //System.out.println(Thread.currentThread().getName() + "\tawait");
            }

            //2 干活
            num--;
            System.out.println(Thread.currentThread().getName() + "\t消费num=" + num);
            TimeUnit.SECONDS.sleep(2);

            //3 唤醒
            condition.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            //释放锁
            lock.unlock();
        }
    }

    void produce() {
        //加锁
        lock.lock();
        try {
            //1 判断
            for (; num == 5; condition.await()) {
                //System.out.println(Thread.currentThread().getName() + "\tawait");
            }

            //2 干活
            num++;
            System.out.println(Thread.currentThread().getName() + "\t生产num=" + num);
            TimeUnit.SECONDS.sleep(2);

            //3 唤醒
            condition.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally{
            //释放锁
            lock.unlock();
        }
    }
}